
from openpyxl import load_workbook
from datetime import datetime
import sys
import tools

def getCols(stratChar,endChar):
    return [chr(i) for i in range(ord(stratChar), ord(endChar)+1)]

if __name__=="__main__":

    print('Excel文件只能一个一个的翻译')
    s = datetime.now()

    icols = input('请输入列:')
    sch = icols.split(' ')[0]
    ech = icols.split(' ')[1]

    irows = input('请输入行:')
    srow = int(irows.split(' ')[0])
    erow = int(irows.split(' ')[1])

    cols = getCols(sch, ech)
    rows = list(range(srow, erow+1))

    '''获取appid 和 appkey'''
    idkey = tools.getidkey()
    appid = idkey[0]
    appkey = idkey[1]

    fromLan, toLan = tools.getLanguage()

    files = tools.getFilesList('xlsx')
    if len(files) <= 0:
        print('没有找到pptx文件')
        input('按任意键退出...')
        sys.exit(0)

    file = files[0]
    name = file.split('.')[0]

    res = []
    hanzi = []
    sumHanzi = 0
    wb = load_workbook(f'{name}.xlsx')
    ws = wb.active

    plen = len(cols) * len(rows)
    pcount = 1
    try:
        for col in cols:
            print('************************************')
            for row in rows:
                index = col+str(row)
                txt =  tools.handle_text(ws[index].value,fromLan)
                if tools.jump_text(txt) :continue
                tran_text = tools.tran(txt, fromLan, toLan, appid, appkey)
                if toLan == 'zh': hanzi.append(tran_text + "\n");sumHanzi+=len(tran_text)
                print(tools.get_process(pcount, plen) + '---' + txt)
                ws[index].value = txt+"\n"+tran_text
                pcount +=1
        wb.save(f'机翻-{name}.xlsx')
        if toLan == 'zh':
            with open(f'汉字-{name}.txt', 'w', encoding='utf-8') as resfilehanzi:
                resfilehanzi.writelines(hanzi)
            print(f'共计:{sumHanzi}个汉字')

        print(f"完成！共计:{tools.diff_time(s, datetime.now())}分钟")
    except Exception as e:
        print(e)
        wb.save(f'机翻-{name}.xlsx')
        if toLan == 'zh':
            with open(f'汉字-{name}.txt', 'w', encoding='utf-8') as resfilehanzi:
                resfilehanzi.writelines(hanzi)
            print(f'共计:{sumHanzi}个汉字')

        print(f"完成！共计:{tools.diff_time(s, datetime.now())}分钟")
    input('按任意键退出...')